package com.jilian.mydemo.modul.order.ui;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.Nullable;

import com.alibaba.fastjson.JSONObject;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.NetworkUtil;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.route.BikingRoutePlanOption;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.jilian.mydemo.MyApplication;
import com.jilian.mydemo.R;
import com.jilian.mydemo.base.BaseActivity;
import com.jilian.mydemo.base.BaseDto;
import com.jilian.mydemo.common.dto.PlanPathListDto;
import com.jilian.mydemo.modul.order.viewmodel.OrderViewModel;
import com.jilian.mydemo.utils.EmptyUtils;
import com.jilian.mydemo.utils.ToastUitl;
import com.jilian.mydemo.utils.overlayutil.BikingRouteOverlay;
import com.jilian.mydemo.utils.overlayutil.MyBikingRouteOverlay;

import java.util.ArrayList;
import java.util.List;

/**
 * 地图详情
 */
public class MapViewActivity extends BaseActivity implements BDLocationListener {
    private MapView mapView;
    //地图对象
    private BaiduMap baiduMap;
    private OrderViewModel viewModel;
    private RoutePlanSearch mSearch;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.removeActivity(this);
        mSearch.destroy();
    }

    @Override
    protected void createViewModel() {
        viewModel = ViewModelProviders.of(this).get(OrderViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_mapview;
    }

    @Override
    public void initView() {
        setNormalTitle("地图", v -> finish());
        mapView = (MapView) findViewById(R.id.mapView);
        baiduMap = mapView.getMap();
    }

    @Override
    public void initData() {
        //startLocationCilent();
        mSearch = RoutePlanSearch.newInstance();

        getMapData();
    }

    /**
     * 开启定位
     */
    private void startLocationCilent() {
        // 申请权限
        MyApplication.getInstance().mLocationClient.start();
        MyApplication.getInstance().mLocationClient.registerLocationListener(this);
    }

    @Override
    public void initListener() {
        OnGetRoutePlanResultListener listener = new OnGetRoutePlanResultListener() {
            @Override
            public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

            }

            @Override
            public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

            }

            @Override
            public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

            }

            @Override
            public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {

            }

            @Override
            public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

            }

            @Override
            public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {
                //创建BikingRouteOverlay实例
                MyBikingRouteOverlay overlay = new MyBikingRouteOverlay(baiduMap);
                if (EmptyUtils.isNotEmpty(bikingRouteResult.getRouteLines())) {
                    //获取路径规划数据,(以返回的第一条路线为例）
                    //为BikingRouteOverlay实例设置数据
                    overlay.setData(bikingRouteResult.getRouteLines().get(0));
                    //在地图上绘制BikingRouteOverlay
                    overlay.addToMap();
                }
                else{
                    showPointsInBaiduMap(mPointList,null);
                }
            }
        };
        mSearch.setOnGetRoutePlanResultListener(listener);
    }

    private double currentLat;//当前位置的维度
    private double currentLon;//当前位置的维度

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        if (bdLocation != null) {
            currentLat = bdLocation.getLatitude();
            currentLon = bdLocation.getLongitude();
            initMapLocation(currentLat, currentLon);
            MyApplication.getInstance().mLocationClient.stop();

        }
    }

    /**
     * 获取工单地图
     */
    private void getMapData() {
        showLoadingDialog();
        viewModel.planPath();
        viewModel.getPlanPathliveData().observe(this, new Observer<BaseDto<PlanPathListDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<PlanPathListDto> dtoBaseDto) {
                hideLoadingDialog();
                if (dtoBaseDto.isSuccess()) {
                    if (EmptyUtils.isNotEmpty(dtoBaseDto.getData()) && EmptyUtils.isNotEmpty(dtoBaseDto.getData().getList())) {
                        mPointList = new ArrayList<>();
                        for (int i = 0; i < dtoBaseDto.getData().getList().size(); i++) {
                            String latStr = dtoBaseDto.getData().getList().get(i).getLocation().split(",")[0];
                            Double lat = Double.parseDouble(latStr);
                            String lonStr = dtoBaseDto.getData().getList().get(i).getLocation().split(",")[1];
                            Double lon = Double.parseDouble(lonStr);
                            LatLng latLng = new LatLng(lat, lon);
                            mPointList.add(latLng);
                            if (i == 0) {
                                initMapLocation(lat, lon);
                            }
                        }
                        //只有一个点
                        if(EmptyUtils.isNotEmpty(mPointList)&&mPointList.size()==1){
                             showPointsInBaiduMap(mPointList,null);
                        }
                        else{

                            showLinesInBaiduMap(mPointList);
                        }


                    }
                } else {
                    ToastUitl.showImageToastTips(dtoBaseDto.getMsg());
                }
            }
        });
    }

    /**
     * 画线
     *
     * @param mPointList
     */
    private void showLinesInBaiduMap(List<LatLng> mPointList) {
        if (EmptyUtils.isNotEmpty(mPointList) && mPointList.size() > 1) {

            for (int i = mPointList.size() - 1; i >= 1; i--) {

                PlanNode stNode = PlanNode.withLocation(mPointList.get(i));
                PlanNode enNode = PlanNode.withLocation(mPointList.get(i - 1));

                mSearch.bikingSearch((new BikingRoutePlanOption())
                        .from(stNode)
                        .to(enNode)
                        // ridingType  0 普通骑行
                        //            1 电动车骑行
                        // 默认普通骑行
                        .ridingType(1));
            }
        }


    }

    /**
     * 定位到某个坐标点
     *
     * @param latitude
     * @param longitude
     */
    private void initMapLocation(double latitude, double longitude) {
        // 开启定位图层
        baiduMap.setMyLocationEnabled(true);
        // 构造定位数据
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(200)
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(100).latitude(latitude)
                .longitude(longitude).build();
        // 设置定位数据
        baiduMap.setMyLocationData(locData);
        // 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标）
        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                .fromResource(R.drawable.image_now_adress);
        MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, true, mCurrentMarker);
        baiduMap.setMyLocationConfiguration(config);
        // 当不需要定位图层时关闭定位图层
        baiduMap.setMyLocationEnabled(false);

    }

    List<LatLng> mPointList;

    /**
     * 在地图上展示各个点
     *
     * @param pointList
     */
    private void showPointsInBaiduMap(List<LatLng> pointList, Integer resours) {
        if (resours == null) {
            //创建OverlayOptions的集合
            List<OverlayOptions> options = new ArrayList<>();
            for (int i = 0; i < pointList.size(); i++) {
                //构建MarkerOption，用于在地图上添加Marker
                MarkerOptions option = new MarkerOptions();
                option.position(pointList.get(i));
                //构建Marker图标
                option.icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.image_location_target));
                //在地图上添加Marker，并显示
                options.add(option);
                //定义文字所显示的坐标点
            }
            //在地图上批量添加
            baiduMap.addOverlays(options);
        } else {
            //创建OverlayOptions的集合
            List<OverlayOptions> options = new ArrayList<>();
            //构建MarkerOption，用于在地图上添加Marker
            MarkerOptions option = new MarkerOptions();
            option.position(pointList.get(0));
            option.icon(BitmapDescriptorFactory
                    .fromResource(resours));
            //在地图上添加Marker，并显示
            options.add(option);
            //定义文字所显示的坐标点
            //在地图上批量添加
            baiduMap.addOverlays(options);
        }

    }

}
